package com.lyw.springCloud.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lyw.springCloud.dao.AccountDao;
import com.lyw.springCloud.domain.Account;
import com.lyw.springCloud.domain.Order;
import com.lyw.springCloud.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * @Auther liyawei
 * @Date 2022/5/22 11:06
 */

@Slf4j
@Service
public class AccountServiceImpl implements AccountService {

    @Resource
    private AccountDao accountDao;

    @Override
    public void decrease(Order order) {

        log.info("------->account-service中扣减账户余额开始");

        //模拟超时异常：全局事务回滚
        try {
            TimeUnit.SECONDS.sleep(1120);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        LambdaUpdateWrapper<Account> wrapper = new UpdateWrapper<Account>().lambda();
        wrapper.ge(Account::getUserId, order.getUserId());
        Account account = accountDao.selectOne(wrapper);
        account.setTotal(account.getTotal().subtract(order.getMoney()));
        account.setUsed(account.getUsed().add(order.getMoney()));

        accountDao.update(account, wrapper);
    }
}
